package com.ysd.conf;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ysd.common.DataBaseType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@Configuration
public class pageConfig{

    /**
     * 设置数据库分页类型
     */
    @Value("${mybatis-plus.configuration.page-type}")
    private String pageType;


    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(getDbType(pageType)));
        return mybatisPlusInterceptor;
    }


    @Bean
    public DataBaseType dataBaseType() {
        DataBaseType database = new DataBaseType();
        database.setDataBaseName(pageType);
        return database;
    }

    //用于更改tomcat的非法字符限制。去掉一些括号双引号的限制
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> connector.setProperty("relaxedQueryChars", "|{}[]\\"));
        return factory;
    }
    /**
     * @param pageType 类型库类型
     * @return ignore
     */
    public DbType getDbType(String pageType) {
        if (pageType.equals("mysql") || pageType.equals("cobar")) {
            return DbType.MYSQL;
        } else if (pageType.equals("mariadb")) {
            return DbType.MARIADB;
        } else if (pageType.equals("oracle")) {
            return DbType.ORACLE;
        } else if (pageType.equals("sqlserver") || pageType.equals("microsoft")) {
            return DbType.SQL_SERVER2005;
        } else if (pageType.equals("sqlserver2012")) {
            return DbType.SQL_SERVER;
        } else if (pageType.equals("postgresql")) {
            return DbType.POSTGRE_SQL;
        } else if (pageType.equals("dm")) {
            return DbType.DM;
        } else {
            return DbType.OTHER;
        }
    }

}
